Passed
Pull Request — master (#130)
by Jan
01:38
created

ID3Helpers.js ➔ getFramesFromID3Body   C

Complexity

Conditions 10

Size

Total Lines 51
Code Lines 31

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
eloc 31
dl 0
loc 51
rs 5.9999
c 0
b 0
f 0
cc 10

How to fix   Long Method    Complexity   

Long Method

Small methods make your code easier to understand, in particular if combined with a good name. Besides, if your method is small, finding a good name is usually much easier.

For example, if you find yourself adding comments to a method's body, this is usually a good sign to extract the commented part to a new method, and use the comment as a starting point when coming up with a good name for this new method.

Commonly applied refactorings include:

Complexity

Complex classes like ID3Helpers.js ➔ getFramesFromID3Body often do a lot of different things. To break such a class down, we need to identify a cohesive component within that class. A common approach to find such a component is to look for fields/methods that share the same prefixes, or suffixes.

Once you have determined the fields that belong together, you can apply the Extract Class refactoring. If the component makes sense as a sub-class, Extract Subclass is also a candidate, and is often faster.

1
const zlib = require('zlib')
2
const ID3Definitions = require("./ID3Definitions")
3
const ID3Frames = require('./ID3Frames')
4
const ID3Util = require('./ID3Util')
5
6
/**
7
 * Returns array of buffers created by tags specified in the tags argument
8
 * @param tags - Object containing tags to be written
9
 * @returns {Array}
10
 */
11
function createBuffersFromTags(tags) {
12
    const frames = []
13
    if(!tags) {
14
        return frames
15
    }
16
    const rawObject = Object.keys(tags).reduce((acc, val) => {
17
        if(ID3Definitions.FRAME_IDENTIFIERS.v3[val] !== undefined) {
18
            acc[ID3Definitions.FRAME_IDENTIFIERS.v3[val]] = tags[val]
19
        } else if(ID3Definitions.FRAME_IDENTIFIERS.v4[val] !== undefined) {
20
            /**
21
             * Currently, node-id3 always writes ID3 version 3.
22
             * However, version 3 and 4 are very similar, and node-id3 can also read version 4 frames.
23
             * Until version 4 is fully supported, as a workaround, allow writing version 4 frames into a version 3 tag.
24
             * If a reader does not support a v4 frame, it's (per spec) supposed to skip it, so it should not be a problem.
25
             */
26
            acc[ID3Definitions.FRAME_IDENTIFIERS.v4[val]] = tags[val]
27
        } else {
28
            acc[val] = tags[val]
29
        }
30
        return acc
31
    }, {})
32
33
    Object.keys(rawObject).forEach((frameIdentifier) => {
34
        let frame
35
        // Check if invalid frameIdentifier
36
        if(frameIdentifier.length !== 4) {
37
            return
38
        }
39
        if(ID3Frames[frameIdentifier] !== undefined) {
40
            frame = ID3Frames[frameIdentifier].create(rawObject[frameIdentifier], 3)
41
        } else if(frameIdentifier.startsWith('T')) {
42
            frame = ID3Frames.GENERIC_TEXT.create(frameIdentifier, rawObject[frameIdentifier], 3)
43
        } else if(frameIdentifier.startsWith('W')) {
44
            if(ID3Util.getSpecOptions(frameIdentifier, 3).multiple && rawObject[frameIdentifier] instanceof Array && rawObject[frameIdentifier].length > 0) {
45
                frame = Buffer.alloc(0)
46
                // deduplicate array
47
                for(const url of [...new Set(rawObject[frameIdentifier])]) {
48
                    frame = Buffer.concat([frame, ID3Frames.GENERIC_URL.create(frameIdentifier, url, 3)])
49
                }
50
            } else {
51
                frame = ID3Frames.GENERIC_URL.create(frameIdentifier, rawObject[frameIdentifier], 3)
52
            }
53
        }
54
55
        if (frame && frame instanceof Buffer) {
56
            frames.push(frame)
57
        }
58
    })
59
60
    return frames
61
}
62
63
/**
64
 * Return a buffer with the frames for the specified tags
65
 * @param tags - Object containing tags to be written
66
 * @returns {Buffer}
67
 */
68
module.exports.createBufferFromTags = function(tags) {
69
    return Buffer.concat(createBuffersFromTags(tags))
70
}
71
72
module.exports.getTagsFromBuffer = function(filebuffer, options) {
73
    const framePosition = ID3Util.getFramePosition(filebuffer)
74
    if(framePosition === -1) {
75
        return getTagsFromFrames([], 3, options)
76
    }
77
    const frameSize = ID3Util.decodeSize(filebuffer.slice(framePosition + 6, framePosition + 10)) + 10
78
    const ID3Frame = Buffer.alloc(frameSize + 1)
79
    filebuffer.copy(ID3Frame, 0, framePosition)
80
    //ID3 version e.g. 3 if ID3v2.3.0
81
    const ID3Version = ID3Frame[3]
82
    const tagFlags = ID3Util.parseTagHeaderFlags(ID3Frame)
83
    let extendedHeaderOffset = 0
84
    if(tagFlags.extendedHeader) {
85
        if(ID3Version === 3) {
86
            extendedHeaderOffset = 4 + filebuffer.readUInt32BE(10)
87
        } else if(ID3Version === 4) {
88
            extendedHeaderOffset = ID3Util.decodeSize(filebuffer.slice(10, 14))
89
        }
90
    }
91
    const ID3FrameBody = Buffer.alloc(frameSize - 10 - extendedHeaderOffset)
92
    filebuffer.copy(ID3FrameBody, 0, framePosition + 10 + extendedHeaderOffset)
93
94
    const frames = getFramesFromID3Body(ID3FrameBody, ID3Version, options)
95
96
    return getTagsFromFrames(frames, ID3Version, options)
97
}
98
99
function isFrameDiscardedByOptions(frameIdentifier, options) {
100
    if(options.exclude instanceof Array && options.exclude.includes(frameIdentifier)) {
101
        return true
102
    }
103
104
    return options.include instanceof Array && !options.include.includes(frameIdentifier)
105
}
106
107
function getFramesFromID3Body(ID3TagBody, ID3Version, options = {}) {
108
    let currentPosition = 0
109
    const frames = []
110
    if(!ID3TagBody || !(ID3TagBody instanceof Buffer)) {
111
        return frames
112
    }
113
114
    const frameIdentifierSize = (ID3Version === 2) ? 3 : 4
115
    const frameHeaderSize = (ID3Version === 2) ? 6 : 10
116
117
    while(currentPosition < ID3TagBody.length && ID3TagBody[currentPosition] !== 0x00) {
118
        const frameHeader = Buffer.alloc(frameHeaderSize)
119
        ID3TagBody.copy(frameHeader, 0, currentPosition)
120
121
        const frameIdentifier = frameHeader.toString('utf8', 0, frameIdentifierSize)
122
        const decodeSize = ID3Version === 4
123
        const frameBodySize = ID3Util.getFrameSize(frameHeader, decodeSize, ID3Version)
124
        // It's possible to discard frames via options.exclude/options.include
125
        // If that is the case, skip this frame and continue with the next
126
        if(isFrameDiscardedByOptions(frameIdentifier, options)) {
127
            currentPosition += frameBodySize + frameHeaderSize
128
            continue
129
        }
130
        // Prevent errors when the current frame's size exceeds the remaining tags size (e.g. due to broken size bytes).
131
        if(frameBodySize + frameHeaderSize > (ID3TagBody.length - currentPosition)) {
132
            break
133
        }
134
135
        const frameHeaderFlags = ID3Util.parseFrameHeaderFlags(frameHeader, ID3Version)
136
        // Frames may have a 32-bit data length indicator appended after their header,
137
        // if that is the case, the real body starts after those 4 bytes.
138
        const frameBodyOffset = frameHeaderFlags.dataLengthIndicator ? 4 : 0
139
        const bodyFrameBuffer = Buffer.alloc(frameBodySize - frameBodyOffset)
140
        ID3TagBody.copy(bodyFrameBuffer, 0, currentPosition + frameHeaderSize + frameBodyOffset)
141
142
        const frame = {
143
            name: frameIdentifier,
144
            flags: frameHeaderFlags,
145
            body: frameHeaderFlags.unsynchronisation ? ID3Util.processUnsynchronisedBuffer(bodyFrameBuffer) : bodyFrameBuffer
146
        }
147
        if(frameHeaderFlags.dataLengthIndicator) {
148
            frame.dataLengthIndicator = ID3TagBody.readInt32BE(currentPosition + frameHeaderSize)
149
        }
150
        frames.push(frame)
151
152
        //  Size of frame body + its header
153
        currentPosition += frameBodySize + frameHeaderSize
154
    }
155
156
    return frames
157
}
158
159
function decompressFrame(frame) {
160
    if(frame.body.length < 5 || frame.dataLengthIndicator === undefined) {
161
        return null
162
    }
163
164
    /*
165
    * ID3 spec defines that compression is stored in ZLIB format, but doesn't specify if header is present or not.
166
    * ZLIB has a 2-byte header.
167
    * 1. try if header + body decompression
168
    * 2. else try if header is not stored (assume that all content is deflated "body")
169
    * 3. else try if inflation works if the header is omitted (implementation dependent)
170
    * */
171
    let decompressedBody
172
    try {
173
        decompressedBody = zlib.inflateSync(frame.body)
174
    } catch (e) {
175
        try {
176
            decompressedBody = zlib.inflateRawSync(frame.body)
177
        } catch (e) {
178
            try {
179
                decompressedBody = zlib.inflateRawSync(frame.body.slice(2))
180
            } catch (e) {
181
                return null
182
            }
183
        }
184
    }
185
    if(decompressedBody.length !== frame.dataLengthIndicator) {
186
        return null
187
    }
188
    return decompressedBody
189
}
190
191
function getTagsFromFrames(frames, ID3Version, options = {}) {
192
    const tags = { }
193
    const raw = { }
194
195
    frames.forEach((frame) => {
196
        let frameIdentifier
197
        let identifier
198
        if(ID3Version === 2) {
199
            frameIdentifier = ID3Definitions.FRAME_IDENTIFIERS.v3[ID3Definitions.FRAME_INTERNAL_IDENTIFIERS.v2[frame.name]]
200
            identifier = ID3Definitions.FRAME_INTERNAL_IDENTIFIERS.v2[frame.name]
201
        } else if(ID3Version === 3 || ID3Version === 4) {
202
            /**
203
             * Due to their similarity, it's possible to mix v3 and v4 frames even if they don't exist in their corrosponding spec.
204
             * Programs like Mp3tag allow you to do so, so we should allow reading e.g. v4 frames from a v3 ID3 Tag
205
             */
206
            frameIdentifier = frame.name
207
            identifier = ID3Definitions.FRAME_INTERNAL_IDENTIFIERS.v3[frame.name] || ID3Definitions.FRAME_INTERNAL_IDENTIFIERS.v4[frame.name]
208
        }
209
210
        if(!frameIdentifier || !identifier || frame.flags.encryption) {
211
            return
212
        }
213
214
        if(frame.flags.compression) {
215
            const decompressedBody = decompressFrame(frame)
216
            if(!decompressedBody) {
217
                return
218
            }
219
            frame.body = decompressedBody
220
        }
221
222
        let decoded
223
        if(ID3Frames[frameIdentifier]) {
224
            decoded = ID3Frames[frameIdentifier].read(frame.body, ID3Version)
225
        } else if(frameIdentifier.startsWith('T')) {
226
            decoded = ID3Frames.GENERIC_TEXT.read(frame.body, ID3Version)
227
        } else if(frameIdentifier.startsWith('W')) {
228
            decoded = ID3Frames.GENERIC_URL.read(frame.body, ID3Version)
229
        }
230
231
        if(!decoded) {
232
            return
233
        }
234
235
        if(ID3Util.getSpecOptions(frameIdentifier, ID3Version).multiple) {
236
            if(!options.onlyRaw) {
237
                if(!tags[identifier]) {
238
                    tags[identifier] = []
239
                }
240
                tags[identifier].push(decoded)
241
            }
242
            if(!options.noRaw) {
243
                if(!raw[frameIdentifier]) {
244
                    raw[frameIdentifier] = []
245
                }
246
                raw[frameIdentifier].push(decoded)
247
            }
248
        } else {
249
            if(!options.onlyRaw) {
250
                tags[identifier] = decoded
251
            }
252
            if(!options.noRaw) {
253
                raw[frameIdentifier] = decoded
254
            }
255
        }
256
    })
257
258
    if(options.onlyRaw) {
259
        return raw
260
    }
261
    if(options.noRaw) {
262
        return tags
263
    }
264
265
    tags.raw = raw
266
    return tags
267
}
268
269
module.exports.getTagsFromID3Body = function(body) {
270
    return getTagsFromFrames(getFramesFromID3Body(body, 3), 3)
271
}
272